// 等待文档完全加载
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.forEach(function(tooltipTriggerEl) {
        new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;
            
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // 轮播图自动播放
    var myCarousel = document.querySelector('#heroCarousel');
    if (myCarousel) {
        new bootstrap.Carousel(myCarousel, {
            interval: 6000
        });
    }
    
    // 返回顶部按钮
    var scrollToTopBtn = document.querySelector('.scroll-to-top');
    if (scrollToTopBtn) {
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                scrollToTopBtn.style.display = "block";
            } else {
                scrollToTopBtn.style.display = "none";
            }
        });
        
        scrollToTopBtn.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }
    
    // 导航栏滚动效果
    const navbar = document.querySelector('.navbar');
    if (navbar) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        });
    }
    
    // 滚动动画
    const animatedElements = document.querySelectorAll('.animate-on-scroll');
    if (animatedElements.length > 0) {
        // 使用标记避免重复初始化
        if (!window.animationObserverInitialized) {
            window.animationObserverInitialized = true;
            
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('animated');
                        // 确保动画只触发一次
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.15,
                rootMargin: '0px 0px -10% 0px'
            });
            
            animatedElements.forEach(element => {
                // 检查是否已经添加了animated类
                if (!element.classList.contains('animated')) {
                    observer.observe(element);
                }
            });
        }
    }
    
    // 数字计数动画
    const countElements = document.querySelectorAll('.count-up');
    if (countElements.length > 0) {
        const countObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const target = entry.target;
                    const countTo = parseInt(target.getAttribute('data-count'));
                    let count = 0;
                    const duration = 2000; // 2秒内完成
                    const interval = Math.ceil(duration / countTo);
                    
                    const counter = setInterval(() => {
                        count += 1;
                        target.textContent = count;
                        
                        if (count >= countTo) {
                            clearInterval(counter);
                        }
                    }, interval);
                    
                    countObserver.unobserve(target);
                }
            });
        }, {
            threshold: 0.5
        });
        
        countElements.forEach(element => {
            countObserver.observe(element);
        });
    }
    
    // 过滤系统
    const filterBtns = document.querySelectorAll('.filter-btn');
    if (filterBtns.length > 0) {
        filterBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                const filterValue = this.getAttribute('data-filter');
                const items = document.querySelectorAll('.filter-item');
                
                // 更新按钮状态
                filterBtns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                
                // 过滤项目
                items.forEach(item => {
                    if (filterValue === 'all') {
                        item.style.display = 'block';
                        setTimeout(() => {
                            item.classList.remove('fade-out');
                            item.classList.add('fade-in');
                        }, 50);
                    } else if (item.classList.contains(filterValue)) {
                        item.style.display = 'block';
                        setTimeout(() => {
                            item.classList.remove('fade-out');
                            item.classList.add('fade-in');
                        }, 50);
                    } else {
                        item.classList.remove('fade-in');
                        item.classList.add('fade-out');
                        setTimeout(() => {
                            item.style.display = 'none';
                        }, 300);
                    }
                });
            });
        });
    }
    
    // 添加视差滚动效果
    const parallaxElements = document.querySelectorAll('.parallax');
    if (parallaxElements.length > 0) {
        window.addEventListener('scroll', () => {
            const scrollY = window.scrollY;
            
            parallaxElements.forEach(element => {
                const speed = element.getAttribute('data-speed') || 0.1;
                element.style.transform = `translateY(${scrollY * speed}px)`;
            });
        });
    }
    
    // 响应式导航菜单增强
    const navToggler = document.querySelector('.navbar-toggler');
    if (navToggler) {
        navToggler.addEventListener('click', function() {
            document.body.classList.toggle('menu-open');
        });
    }
    
    // 添加响应式表格支持
    const tables = document.querySelectorAll('table');
    tables.forEach(table => {
        const wrapper = document.createElement('div');
        wrapper.classList.add('table-responsive');
        table.parentNode.insertBefore(wrapper, table);
        wrapper.appendChild(table);
    });
    
    // 初始化滚动到顶部按钮
    initScrollToTop();
    
    // 初始化数字计数动画
    initCountUp();
    
    // 初始化轮播图
    initCarousel();
    
    // 添加导航栏滚动效果
    initNavbarScroll();
});

// 滚动到顶部按钮功能
function initScrollToTop() {
    const scrollBtn = document.querySelector('.scroll-to-top');
    
    if (scrollBtn) {
        // 显示/隐藏按钮
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                scrollBtn.classList.add('show');
            } else {
                scrollBtn.classList.remove('show');
            }
        });
        
        // 点击滚动到顶部
        scrollBtn.addEventListener('click', function(e) {
            e.preventDefault();
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }
}

// 数字计数动画
function initCountUp() {
    const countElements = document.querySelectorAll('.count-up');
    
    if (countElements.length > 0 && !window.countUpInitialized) {
        window.countUpInitialized = true;
        
        const animateCount = function(element) {
            if(element.classList.contains('counted')) return;
            
            element.classList.add('counted');
            const finalValue = parseInt(element.getAttribute('data-count'), 10);
            const duration = 2000; // 持续2秒
            const startTime = performance.now();
            
            const updateCount = function() {
                const currentTime = performance.now();
                const elapsedTime = currentTime - startTime;
                
                if (elapsedTime < duration) {
                    const progress = elapsedTime / duration;
                    const easedProgress = easeOutQuad(progress);
                    const currentValue = Math.floor(easedProgress * finalValue);
                    element.textContent = currentValue;
                    
                    requestAnimationFrame(updateCount);
                } else {
                    element.textContent = finalValue;
                }
            };
            
            requestAnimationFrame(updateCount);
        };
        
        // 缓动函数
        const easeOutQuad = function(t) {
            return t * (2 - t);
        };
        
        // 使用Intersection Observer检测何时元素进入视口
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    animateCount(entry.target);
                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.1
        });
        
        countElements.forEach(element => {
            observer.observe(element);
        });
    }
}

// 初始化轮播图
function initCarousel() {
    const carousels = document.querySelectorAll('.carousel');
    
    carousels.forEach(carousel => {
        if (!carousel.classList.contains('initialized')) {
            carousel.classList.add('initialized');
            
            new bootstrap.Carousel(carousel, {
                interval: parseInt(carousel.getAttribute('data-interval') || 5000),
                pause: carousel.getAttribute('data-pause') !== 'false',
                wrap: carousel.getAttribute('data-wrap') !== 'false'
            });
        }
    });
}

// 导航栏滚动效果
function initNavbarScroll() {
    const navbar = document.querySelector('.navbar');
    
    if (navbar && !navbar.classList.contains('scroll-initialized')) {
        navbar.classList.add('scroll-initialized');
        
        window.addEventListener('scroll', () => {
            if (window.scrollY > 50) {
                navbar.classList.add('navbar-scrolled');
            } else {
                navbar.classList.remove('navbar-scrolled');
            }
        });
        
        // 初次加载也检查
        if (window.scrollY > 50) {
            navbar.classList.add('navbar-scrolled');
        }
    }
}

// 表单验证
function validateForm(formId) {
    const form = document.getElementById(formId);
    if (!form) return true;
    
    let isValid = true;
    const inputs = form.querySelectorAll('[required]');
    
    inputs.forEach(input => {
        if (!input.value.trim()) {
            input.classList.add('is-invalid');
            isValid = false;
        } else {
            input.classList.remove('is-invalid');
        }
    });
    
    return isValid;
}

// AJAX加载更多内容
function loadMore(endpoint, containerId, button) {
    const container = document.getElementById(containerId);
    const page = parseInt(button.getAttribute('data-page')) || 1;
    const nextPage = page + 1;
    
    button.disabled = true;
    button.innerHTML = '加载中...';
    
    fetch(`${endpoint}?page=${nextPage}`)
        .then(response => response.json())
        .then(data => {
            if (data.html) {
                container.insertAdjacentHTML('beforeend', data.html);
                button.setAttribute('data-page', nextPage);
                button.disabled = false;
                button.innerHTML = '加载更多';
                
                if (!data.has_next) {
                    button.style.display = 'none';
                }
            } else {
                button.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('加载更多内容时出错:', error);
            button.disabled = false;
            button.innerHTML = '重试';
        });
}
